package vip.guzb.sample.threadpool.step01;

import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * 只有一个线程的线程池
 * 池中的唯一线程在等待一段时间后，如果没有任务可执行，则结束运行。
 * 如果后续有新任务提交进来，则新开线程
 *
 * @author 顾志兵
 * @mail ipiger@163.com
 * @since 2024-04-08
 */
public class SingleThreadPoolExecutor2 implements Executor {

    private final Queue<Runnable> tasks = new LinkedBlockingDeque<>();

    private int maxIdleMilliSeconds = 3000;

    private volatile int idleMilliseconds = 0;

    private TaskRunner runner;

    @Override
    public void execute(Runnable task) {
        tasks.offer(task);
        if (!runner.isAlive()) {
            System.out.println("使用新线程执行任务");
            runner = new TaskRunner();
            runner.start();
        }
    }

    public SingleThreadPoolExecutor2() {
        runner = new TaskRunner();
        runner.start();
    }

    class TaskRunner extends Thread {
        @Override
        public void run() {
            Runnable task;
            while (true) {
                task = tasks.poll();
                if (task != null) {
                    task.run();
                    continue;
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                    idleMilliseconds += 10;
                    if (idleMilliseconds > maxIdleMilliSeconds) {
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }
}
